<?php

class Controller_Base extends \Controller_Template_Twig {

    protected $user = null;

    public $auth_required = FALSE;

    public $secure_actions = FALSE;

    /**
     * The before() method is called before your controller action.
     * In our template controller we override this method so that we can
     * set up default values. These variables are then available to our
     * controllers if they need to be modified.
     */
    public function before()
    {
        parent::before();

        $action_name = $this->request->action;
        $this->logged_in = (bool) \Auth::check();

        if ((is_array($this->secure_actions) && array_key_exists($action_name, $this->secure_actions)))
	    {
		    if (! $this->logged_in)
            {
			    \Output::redirect('/users/login');
		    }
	    }

        if ($this->logged_in)
        {
            $this->user = \Auth::instance()->get_user_array(array('id', 'group', 'last_login'));
            $this->user_id = $this->user['id'][1];
        }

        if ($this->auto_render)
  	    {
  	    	$this->template->title   = '';
  			$this->template->styles = array();
  			$this->template->scripts = array();
            $this->template->request = array();
            $this->template->logged_in = $this->logged_in;

            if ($this->logged_in)
            {
                $this->template->user_name = $this->user['screen_name'];
            }
        }
    }

    public function after()
    {
        if ($this->auto_render)
        {
            $app = array(
                'base_url' => \Fuel::generate_base_url(),
                'user' => (! $this->logged_in) ? null : array(
                    'id' => $this->user_id,
                    'name' => $this->user['screen_name'],
                )
            );

            $request = array(
                'ajax' => \Input::is_ajax()
            );

            $styles = array(
                'http://fonts.googleapis.com/css?family=Philosopher&subset=cyrillic,latin',
                'reset.css',
                'style.css',
			);

			$scripts = array(
				'http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js',
                //'jquery.ajaxy.min.js',
                //'jquery.tmpl.min.js',
                //'jquery.tmplPlus.min.js',
                //'base.js',
			);

            $this->template->app = json_encode( $app );
            $this->template->styles = array_merge($styles, $this->template->styles);
            $this->template->scripts = array_merge($scripts, $this->template->scripts);
            $this->template->request = array_merge($request, $this->template->request);
        }

        parent::after();
    }

    public function action_404()
    {
        $this->template->title = 'Not Found';
    }

}
